import {
  Component,
  Optional,
  Inject,
  ViewChild,
  HostBinding,
  HostListener,
  forwardRef,
} from '@angular/core';

import {
  NgModel,
  NG_VALUE_ACCESSOR,
  NG_VALIDATORS,
  NG_ASYNC_VALIDATORS,
} from '@angular/forms';

import { ElementBase } from '../element-base';

@Component({
  selector: 'fui-switch',
  templateUrl: './switch.component.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => SwitchComponent),
    multi: true,
  }],
})
export class SwitchComponent extends ElementBase<boolean> {
  @HostBinding('class.fui-switch') hostClass = true;
  @ViewChild(NgModel, { static: true }) model: NgModel;

  @HostBinding('class.selected')
  get selected() {
    return this.value;
  }

  @HostBinding('class.disabled')
  get isDisabled() {
    return this.disabled;
  }

  @HostBinding('class.readonly')
  get isReadonly() {
    return this.readonly;
  }

  @HostListener('click', ['$event'])
  onClick(e: MouseEvent): void {
    e.preventDefault();
    if (!this.disabled && !this.readonly) {
      this.value = !this.value;
      this.markAsDirty();
    }
  }

  constructor(
    @Optional() @Inject(NG_VALIDATORS) validators: Array<any>,
    @Optional() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<any>,
  ) {
    super(validators, asyncValidators);
  }

}
